package com.liuche.pictureserver.common.exception;

import com.liuche.pictureserver.common.resp.BaseResponse;
import com.liuche.pictureserver.common.resp.ResUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;

/**
 * @author liuche
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 自定义业务异常
     *
     * @param e 异常信息
     * @return 结果
     */
    @ExceptionHandler(BizException.class)
    public BaseResponse<?> businessExceptionHandler(BizException e) {
        log.error("BizException", e);
        return ResUtils.error(e.getCode(), e.getMessage());
    }

    /**
     * 参数校验异常
     *
     * @param e 异常信息
     * @return 结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException", e);
        BindingResult bindingResult = e.getBindingResult();
        int errorCode = ErrorCode.PARAMS_ERROR.getCode();
        StringBuilder sb = new StringBuilder();
        Optional.of(bindingResult.getFieldErrors()).ifPresent(errors -> errors.forEach(error ->
                sb.append(error.getField())
                        .append(" ")
                        .append(error.getDefaultMessage())
                        .append(", 当前值: '")
                        .append(error.getRejectedValue())
                        .append("'; ")

        ));

        // 错误信息
        String errorMessage = sb.toString();
        return ResUtils.error(errorCode, errorMessage);
    }

    /**
     * 其他异常
     *
     * @param e 异常信息
     * @return 结果
     */
    @ExceptionHandler(Exception.class)
    public BaseResponse<?> runtimeExceptionHandler(Exception e) {
        log.error("RuntimeException", e);
        return ResUtils.error(ErrorCode.SYSTEM_ERROR, "系统开小差");
    }
}

